package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.AlipayPreBean;
import com.ekuaitu.kuaitu.bean.CommitCertificateBean;
import com.ekuaitu.kuaitu.bean.DepositBikeResultEvent;
import com.ekuaitu.kuaitu.bean.WXPreBean;
import com.ekuaitu.kuaitu.payment.AlipayUtils;
import com.ekuaitu.kuaitu.payment.WXPayUtils;
import com.ekuaitu.kuaitu.utils.CheckRegexUtils;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BikeCertificateActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.deposit_return)
    ImageView depositReturn;
    @BindView(R.id.deposit_toolbar)
    AutoRelativeLayout depositToolbar;
    @BindView(R.id.deposit_ll)
    AutoLinearLayout depositLl;
    @BindView(R.id.deposit_weiXin)
    ImageView depositWeiXin;
    @BindView(R.id.deposit_button_weiXin)
    RadioButton depositButtonWeiXin;
    @BindView(R.id.deposit_button_zfb)
    RadioButton depositButtonZfb;
    @BindView(R.id.deposit_bike_commit)
    TextView depositBikeCommit;
    @BindView(R.id.activity_deposit)
    AutoLinearLayout activityDeposit;
    @BindView(R.id.progress_bar)
    RelativeLayout progressBar;
    @BindView(R.id.bike_certificate_title)
    TextView bikeCertificateTitle;
    @BindView(R.id.image_dot1)
    ImageView imageDot1;
    @BindView(R.id.image_dot2)
    ImageView imageDot2;
    @BindView(R.id.line_deposit_right)
    View lineDepositRight;
    @BindView(R.id.line_name_left)
    View lineNameLeft;
    @BindView(R.id.image_dot3)
    ImageView imageDot3;
    @BindView(R.id.image_dot4)
    ImageView imageDot4;
    @BindView(R.id.certificate_ll_jbzj)
    AutoLinearLayout certificateLlJbzj;
    @BindView(R.id.layout_deposit)
    AutoLinearLayout layoutDeposit;
    @BindView(R.id.bike_deposit_wx)
    AutoRelativeLayout bikeDepositWx;
    @BindView(R.id.bike_deposit_zfb)
    AutoRelativeLayout bikeDepositZfb;
    @BindView(R.id.bike_deposit_line)
    View bikeDepositLine;
    @BindView(R.id.activity_idName)
    EditText activityIdName;
    @BindView(R.id.activity_idNum)
    EditText activityIdNum;
    @BindView(R.id.activity_idCommit)
    TextView activityIdCommit;
    @BindView(R.id.deposit_money)
    TextView depositMoney;
    @BindView(R.id.layout_name)
    AutoLinearLayout layoutName;


    private Context mContext = this;
    private int payMethod = 0;
    private LatLng curPosition;
    private AMapLocationClient mLocationClient;
    private int certificateStatus;
    private int identityStatus;

    @Override
    public int getLayoutId() {
        return R.layout.activity_bike_certificate;
    }

    @Override
    public void initData() {
        super.initData();
        certificateStatus = getIntent().getIntExtra("certificateStatus", 400);
        identityStatus = getIntent().getIntExtra(SharedPreferencesKey.IDENTITY_STATUS, 11);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        if (certificateStatus == 401) {
            //显示可用的支付方式

            if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
                bikeDepositWx.setVisibility(View.VISIBLE);
                bikeDepositZfb.setVisibility(View.VISIBLE);
                bikeDepositLine.setVisibility(View.VISIBLE);
                depositButtonWeiXin.setChecked(true);
                depositButtonZfb.setChecked(false);
                payMethod = 1;
            } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
                bikeDepositWx.setVisibility(View.VISIBLE);
                bikeDepositZfb.setVisibility(View.GONE);
                bikeDepositLine.setVisibility(View.GONE);
                depositButtonWeiXin.setChecked(true);
                depositButtonZfb.setChecked(false);
                payMethod = 1;
            } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
                bikeDepositWx.setVisibility(View.GONE);
                bikeDepositZfb.setVisibility(View.VISIBLE);
                bikeDepositLine.setVisibility(View.GONE);
                depositButtonWeiXin.setChecked(false);
                depositButtonZfb.setChecked(true);
                payMethod = 2;
            } else {
                bikeDepositWx.setVisibility(View.GONE);
                bikeDepositZfb.setVisibility(View.GONE);
                bikeDepositLine.setVisibility(View.GONE);
                payMethod = 0;
            }
            layoutDeposit.setVisibility(View.VISIBLE);
            layoutName.setVisibility(View.GONE);
            imageDot2.setImageResource(R.drawable.icon_jxz);
            if (identityStatus == 13) {
                lineDepositRight.setBackgroundResource(R.color.colorPrimary);
                lineNameLeft.setBackgroundResource(R.color.colorPrimary);
                imageDot3.setImageResource(R.drawable.icon_tg);
            }
            mLocationClient = new AMapLocationClient(getApplicationContext());
            //设置定位回调监听
            mLocationClient.setLocationListener(this);
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setOnceLocation(true);
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
            depositButtonWeiXin.setChecked(true);

            depositButtonWeiXin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        depositButtonZfb.setChecked(false);
                        payMethod = 1;
                    }
                }
            });

            depositButtonZfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {
                        depositButtonWeiXin.setChecked(false);
                        payMethod = 2;
                    }
                }
            });

            depositMoney.setText(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_BIKE) / 100 + "");

        } else if (certificateStatus == 403) {
            layoutDeposit.setVisibility(View.GONE);
            layoutName.setVisibility(View.VISIBLE);
            imageDot2.setImageResource(R.drawable.icon_tg);
            lineDepositRight.setBackgroundResource(R.color.colorPrimary);
            lineNameLeft.setBackgroundResource(R.color.colorPrimary);
            imageDot3.setImageResource(R.drawable.icon_jxz);
        }
    }

    @Subscribe
    public void onPayResult(DepositBikeResultEvent event) {
        progressBar.setVisibility(View.GONE);
        if (event.payResult == 0) {
            if (identityStatus == 13) {
                finish();
            } else {
                layoutDeposit.setVisibility(View.GONE);
                layoutName.setVisibility(View.VISIBLE);
                imageDot2.setImageResource(R.drawable.icon_tg);
                lineDepositRight.setBackgroundResource(R.color.colorPrimary);
                lineNameLeft.setBackgroundResource(R.color.colorPrimary);
                imageDot3.setImageResource(R.drawable.icon_jxz);
            }
        }
    }


    @OnClick({R.id.deposit_return, R.id.deposit_bike_commit, R.id.activity_idCommit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.deposit_return:
                finish();
                break;
            case R.id.deposit_bike_commit:
                MobclickAgent.onEvent(this, Constants.PAY_DEPOSIT);
                //缴纳保证金
                switch (payMethod) {
                    case 1:
                        getWXpayParams(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_BIKE) + "");
                        break;
                    case 2:
                        getAlipayParams(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_BIKE) + "");
                        break;

                }
                break;
            case R.id.activity_idCommit:
                MobclickAgent.onEvent(this, Constants.REALNAME_AUTHENTICATION);
                if (!TextUtils.isEmpty(activityIdName.getText().toString())) {
                    if (!TextUtils.isEmpty(activityIdNum.getText().toString())) {
                        if (CheckRegexUtils.checkIdCard(activityIdNum.getText().toString())) {
                            confirmIdCardCommit(activityIdName.getText().toString(), activityIdNum.getText().toString());
                        } else {
                            ToastCompat.makeText(mContext, "请输入正确的身份证号码！", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        ToastCompat.makeText(mContext, "请输入身份证号码！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    ToastCompat.makeText(mContext, "请输入姓名！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void getWXpayParams(String chargeValue) {
        String longitude;
        String latitude;
        if (curPosition == null) {
            if (MainActivity.curPosition != null) {
                longitude = MainActivity.curPosition.longitude + "";
                latitude = MainActivity.curPosition.latitude + "";
            } else {
                longitude = "";
                latitude = "";
            }
        } else {
            longitude = curPosition.longitude + "";
            latitude = curPosition.latitude + "";
        }
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatDeposit(MyApplication.getInstance().getRequestFieldMap(), chargeValue, "2", longitude, latitude, "2").enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 1);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(mContext);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getAlipayParams(String chargeValue) {
        String longitude;
        String latitude;
        if (curPosition == null) {
            longitude = "";
            latitude = "";
        } else {
            longitude = curPosition.longitude + "";
            latitude = curPosition.latitude + "";
        }
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayDeposit(MyApplication.getInstance().getRequestFieldMap(), chargeValue, "1", longitude, latitude, "2").enqueue(new Callback<AlipayPreBean>() {
            @Override
            public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 1);
                        String orderInfo = response.body().getAttachment().getStr();
                        AlipayUtils alipayUtils = new AlipayUtils(BikeCertificateActivity.this);
                        alipayUtils.aliPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void confirmIdCardCommit(String name, String idNum) {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).confirmIdCardCommit(MyApplication.getInstance().getRequestFieldMap(), name, idNum).enqueue(new Callback<CommitCertificateBean>() {
            @Override
            public void onResponse(Call<CommitCertificateBean> call, Response<CommitCertificateBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {
                        finish();
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommitCertificateBean> call, Throwable t) {
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        } else {
            mLocationClient.startLocation();
        }
    }

}
